package proxy.dbroute.proxy;

import proxy.dbroute.IOrderService;
import proxy.dbroute.Order;
import proxy.dbroute.OrderService;
import proxy.dbroute.db.DynamicDataSourceEntity;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author zhangxi
 * @date 2021/2/25
 */
public class OrderServiceStaticProxy implements IOrderService {

    private static final String YYYY_REGX = "yyyy";

    private SimpleDateFormat yearFormat = new SimpleDateFormat(YYYY_REGX);

    private OrderService orderService;

    public OrderServiceStaticProxy() {
    }

    public OrderServiceStaticProxy(OrderService orderService) {
        this.orderService = orderService;
    }

    public int createOrder(Order order) {
        Long createTime = order.getCreateTime();
        int dbSource = Integer.parseInt(yearFormat.format(new Date(createTime)));
        System.out.println("静态代理类自动分配到【DB_" +  dbSource + "】数据源处理数据" );
        DynamicDataSourceEntity.set(dbSource);
        orderService.createOrder(order);
        System.out.println("restore数据源");
        DynamicDataSourceEntity.restore();
        return 0;
    }
}
